#!/user/bin/python
# -*- coding:utf-8 -*-
#controller/addComments.py

'''

1.添加评论
2.删除评论

Created on 2011-9-13

@author: zc
 
changeLog:
20111121 返回值增加cid
20120107 返回值增加date
'''

import web
from dbhandle.mysqldb import mysqldb 
from datetime import datetime
from checkkey import checkkey
from controllers.utils import logger
logger = logger.logger()
from config.sqlmap import SQL_GETCID, SQL_DEL_COMMENT

class addComment( object ):
    '''  增加评论    '''

    def POST( self ):
        """ 接受客户端post的消息 """
        data = web.input()
        if checkkey( web.config._session, web.ctx.env ):
            res = self.addcmts( data )
        else:
            res = '{"msg":"203", "errmsg":"session验证未通过.","cid":"","date":""}' 
        return res
    
    
    def addcmts( self, cmtsBody ):
        """ 增加评论
        {
            "uid":"1223",
            "tfid":"1112",
            "comment":"comment body",
            }
         """
        dbo = mysqldb()
        cdate = datetime.now().strftime( "%Y%m%d%H%M%S" )
        res = None
        uid = cmtsBody.uid
        tfid = cmtsBody.tfid
        cmts = cmtsBody.comment.replace( '\n', '' ).replace( '\r', '' )

        cid = dbo.insert( 'comments', seqname = 'cid', _test = True, uid = uid, tfid = tfid, comment = cmts, date = cdate )
        if cid > 0:
                res = '{"msg":"200","cid":"%s","tfid":"%s","date":"%s"}' % ( str( cid ), str( tfid ) , cdate )
        else:
                res = '{"msg":"202", "errmsg":"查询新增评论ID失败.","cid":"","tfid":"%s","date":""}' % str( tfid )
        return res


class delComment( object ):
    '''  删除评论    '''

    def POST( self ):
        """ 接受客户端post的消息 """
        data = web.input()
        if checkkey( web.config._session, web.ctx.env ):
            addres = self.delcmts( data )
        else:
            addres = '{"msg":"203", "errmsg":"session验证未通过.","cid":"%s"}' % str( data )
            
        return addres
    

    def delcmts( self, cmtsBody ):
        """ 删除评论 
        {
            "cid":1223,
            }
         """
        #json_data = simplejson.loads( cmtsBody )
        cid = cmtsBody.cid
        res = None
        dbo = mysqldb()
        sql = SQL_DEL_COMMENT % ( str( cid ) ) 
        row = dbo.execsql( sql )
        if row == -1:
            res = '{"msg":"201", "errmsg":"Delete Comment Faild.","cid":"%s"}' % str( cid )
            logger.error( res )
        else:
            res = '{"msg" : "200", "cid" : "%s"}' % str( cid )

            
        return res
